﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SVN.Net.Controllers
{
    [HandleError]
    public class HomeController : ControllerBase
    {

        public HomeController()
            : base()
        {
        }

        public HomeController(Models.ISVNProvider svn)
            : base(svn)
        {
        }

        public ActionResult Index()
        {
            if (Request.HttpMethod != "POST")
            {
                ViewData["Title"] = "Home Page";
                ViewData["Message"] = "Welcome to SVN.Net!";

                return View();
            }
            else
            {
                return View();
            }
        }

        public ActionResult About()
        {
            ViewData["Title"] = "About Page";

            return View();
        }

        public ActionResult Navigate(string repo, string uid, string pwd)
        {
            if (!string.IsNullOrEmpty(uid))
                UID = uid;
            if (!string.IsNullOrEmpty(pwd))
                PWD = pwd;

            ViewData["repo"] = repo;

            var r = SVN.List(repo, UID, PWD);
            if (!r.Success)
                throw r.Error;

            Models.SVN.ItemCollection items = new SVN.Net.Models.SVN.ItemCollection(repo);
            foreach (System.Xml.XmlNode entry in r.XmlResult.SelectNodes("//lists/list/entry"))
                items.Add(new SVN.Net.Models.SVN.Item(entry, items));
            items.Sort(new Models.SVN.Item());
            return View("Index", items);
        }

        public ActionResult Export(string repo)
        {
            // Export the directory tree from SVN server to local server.
            string localPath = string.Empty;
            byte[] zip = SVN.Export(repo, UID, PWD, ref localPath);
            // Delete the exported directory in local server.
            DeleteWorkingDir(localPath);
            if (zip == null)
                throw new Models.SVN.SvnException("Cannot export from server.");
            return new Misc.SVNExportResult(GlobalApplication.GetName(repo), zip);
        }

    }
}
